package com.dianrui.moonfire.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.baidumap.BaiDuUtils;
import com.dianrui.moonfire.bean.ChangeName;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.GlideUtil;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Description:订单详情
 * User: luoziyin
 * Date: 2020-8-17
 */
public class OrderDetailActivity extends BaseActivity {
    private BaiduMap baiduMap;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.pic)
    ImageView pic;
    @BindView(R.id.nickname)
    TextView nicknames;
    @BindView(R.id.bike_code)
    TextView bikeCode;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.create_time)
    TextView createTime;
    String orderId, startPoints, endPoints;
    List<LatLng> gps = new ArrayList<>();
    @BindView(R.id.sub_feedback)
    Button subBtn;//故障反馈按钮
    @BindView(R.id.sub_feedback_info)
    Button subBtnInfo;//查看反馈按钮

    @Override
    public int getContentViewId() {
        return R.layout.activity_orderdetails;
    }


    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        baiduMap = map.getMap();//获取百度地图的实例
        customInit(true);
        title.setText(getResources().getString(R.string.order_details_title));
        BaiDuUtils.initUI(map);
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                orderId = bundle.getString("order_id");
            }
        }
        baiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                getOrderDetails();
            }
        });
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("face"))) {
            GlideUtil.loadUserImageViewSize(getApplicationContext(), SPUtils.getInstance().getString("face"), pic);
        }

        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("nickname"))) {
            nicknames.setText(SPUtils.getInstance().getString("nickname"));
        }


        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                baiduMap.hideInfoWindow();
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {}
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);

    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }



    @Override
    public void initData() {}

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if(TextUtils.equals(str, EventBusConstants.REFRESH_ORDER_DETAILS)) {
            getOrderDetails();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)//修改昵称后更新本地并上传给后台
    public void onMessageEvent(ChangeName changeName) {
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("nickname"))) {
            nicknames.setText(SPUtils.getInstance().getString("nickname"));
        }

    }

    @SuppressLint("InflateParams")
    private void getOrderDetails() {
        JsonObject orderDetails = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            orderDetails.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        orderDetails.addProperty("order_id", orderId);
        XHttpRequest.getInstance().postRequests(Url.ORDER_DETAILS, orderDetails.toString(),  new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (gps.size()>0) {
                                     gps.clear();
                                }
                                String data = JsonUtils.getJsonStr(result, "data");
                                time.setText(JsonUtils.getJsonStr(data,"duration"));
                                String bikeCodes = "车辆编号:" +JsonUtils.getJsonStr(data,"vehicle_number");
                                bikeCode.setText(bikeCodes);
                                money.setText(JsonUtils.getJsonStr(data,"money"));
                                createTime.setText(JsonUtils.getJsonStr(data,"start_time"));

                                final int feedbackId = StringUtils.toInt(JsonUtils.getJsonStr(data,"feedback_id"));
                                if (feedbackId > 0) {
                                    subBtnInfo.setVisibility(View.VISIBLE);
                                    subBtn.setVisibility(View.GONE);
                                } else if (feedbackId == 0) {
                                    subBtnInfo.setVisibility(View.GONE);
                                    subBtn.setVisibility(View.VISIBLE);
                                }
                                subBtnInfo.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(OrderDetailActivity.this, FeedBackInfoActivity.class);
                                        Bundle bundle=new Bundle();
                                        bundle.putInt("feedbackId", feedbackId);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                    }
                                });
                                final JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("gps");
                                if (jsonArray.length() > 0) {
                                    final LatLng current = new LatLng(jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lng"));
                                    MapStatus mapStatus = new MapStatus.Builder().target(current).zoom(18).build();
                                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                                    map.getMap().setMapStatus(mapStatusUpdate);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        gps.add(new LatLng(jsonArray.optJSONObject(i).optDouble("lat"), jsonArray.optJSONObject(i).getDouble("lng")));
                                    }
                                    //起点
                                    if (jsonArray.length() > 1) {
                                        LayoutInflater inflater = LayoutInflater.from(OrderDetailActivity.this);
                                        View startPointView = inflater.inflate(R.layout.start_point, null);
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", 1);//先把上个界面用bundle存起来以及存下type，方便区别起点和终点
                                        bundle.putString("start", JsonUtils.getJsonStr(data,"start_path"));
                                        BaiDuUtils.startPoints(map, jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("lng"), OrderDetailActivity.this, BitmapDescriptorFactory.fromView(startPointView), bundle);


                                        LayoutInflater inflater1 = LayoutInflater.from(OrderDetailActivity.this);
                                        View endPointView = inflater1.inflate(R.layout.end_point, null);
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putInt("type", 2);
                                        bundle1.putString("end",JsonUtils.getJsonStr(data,"end_path"));
                                        BaiDuUtils.endPoints(map, jsonArray.optJSONObject(0).optDouble("lat"), jsonArray.optJSONObject(0).getDouble("lng"), OrderDetailActivity.this, BitmapDescriptorFactory.fromView(endPointView), bundle1);


                                    } else {//终点
                                        LayoutInflater inflater1 = LayoutInflater.from(OrderDetailActivity.this);
                                        View endPointView = inflater1.inflate(R.layout.end_point, null);
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putInt("type", 2);
                                        bundle1.putString("end", JsonUtils.getJsonStr(data,"end_path"));
                                        BaiDuUtils.endPoints(map, jsonArray.optJSONObject(0).optDouble("lat"), jsonArray.optJSONObject(0).getDouble("lng"), OrderDetailActivity.this, BitmapDescriptorFactory.fromView(endPointView), bundle1);
                                    }
                                    if (gps.size() > 1) {
                                        BaiDuUtils.drawliness(map, gps);
                                    }

                                    baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                                        @Override
                                        public boolean onMarkerClick(Marker marker) {
                                            if (marker.getExtraInfo() != null) {
                                                switch (marker.getExtraInfo().getInt("type")) {//通过type分别判断，这样成功隔离起点终点
                                                    case 1:
                                                        String startPaths = marker.getExtraInfo().getString("start");
                                                        View view = LayoutInflater.from(OrderDetailActivity.this).inflate(R.layout.start_point_bubble, null);
                                                        TextView startTxt = view.findViewById(R.id.start_point_text);
                                                        startTxt.setText(startPaths);
                                                        final LatLng ll = marker.getPosition();
                                                        Point p = baiduMap.getProjection().toScreenLocation(ll);
                                                        LatLng llInfo = baiduMap.getProjection().fromScreenLocation(p);
                                                        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), llInfo, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow);
                                                        break;
                                                    case 2:
                                                        String endPath = marker.getExtraInfo().getString("end");
                                                        View view1 = LayoutInflater.from(OrderDetailActivity.this).inflate(R.layout.end_point_bubble, null);
                                                        TextView endTxt = view1.findViewById(R.id.end_point_text);
                                                        endTxt.setText(endPath);
                                                        final LatLng ll1 = marker.getPosition();
                                                        Point p1 = baiduMap.getProjection().toScreenLocation(ll1);
                                                        LatLng llInfo1 = baiduMap.getProjection().fromScreenLocation(p1);
                                                        InfoWindow mInfoWindow1 = new InfoWindow(BitmapDescriptorFactory.fromView(view1), llInfo1, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow1);
                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }
                                            return true;
                                        }
                                    });
                                }

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick({R.id.back, R.id.sub_feedback})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sub_feedback:
                Intent intent = new Intent(OrderDetailActivity.this, TroubleFeedActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("mv_id", orderId);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
